package com.geomesa.spark.SparkCore;

import com.geomesa.spark.SparkJTS.Operation;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.operation.distance.DistanceOp;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.feature.FeatureCollection;
import org.geotools.geojson.GeoJSON;
import org.geotools.geojson.feature.FeatureJSON;
import org.geotools.geojson.geom.GeometryJSON;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import java.io.*;

public class FeatJson {
    static GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
    public static void main(String[] args) throws IOException {
        //读取本地文件
        FileReader reader = new FileReader("D:/GitProjects/GeoMesa/GeoMesaSpark/src/main/resources/gsmc.txt");
        BufferedReader bufferReader = new BufferedReader(reader);
        String dict = bufferReader.readLine();
        //按行读取文件
        //构造FeatureJSON对象，GeometryJSON保留15位小数
        FeatureJSON featureJSON = new FeatureJSON(new GeometryJSON(15));
        FeatureCollection featureCollection = featureJSON.readFeatureCollection(dict);
        SimpleFeatureType simpleFeatureType = (SimpleFeatureType) featureCollection.getSchema();
        System.out.println(simpleFeatureType.getGeometryDescriptor().getLocalName());
        OutputStream ostream = new ByteArrayOutputStream();
        GeoJSON.write(featureCollection, ostream);
        System.out.println(ostream);

        SimpleFeatureIterator iterator = (SimpleFeatureIterator) featureCollection.features();
        SimpleFeature simpleFeature = iterator.next();
        Geometry geom = (Geometry) simpleFeature.getDefaultGeometry();
        iterator.close();
        System.out.println(geom.getLength());
        System.out.println(geom.getCoordinate());
        System.out.println(geom.getBoundary());
        System.out.println(geom.getGeometryType());

        //新建一个经纬度坐标对象
        Coordinate coordinate1 = new Coordinate(1.357846020181606E7, 4505819.87283728);
        Coordinate[] coordinates2 = geom.getCoordinates();
        Operation op = new Operation();
        //求点到线的距离
        System.out.println("距离："+op.distanceGeo(geometryFactory.createPoint(coordinate1),geometryFactory.createLineString(coordinates2)));
        //求点到线的最近一个点
        System.out.println(DistanceOp.nearestPoints(geometryFactory.createPoint(coordinate1),geometryFactory.createLineString(coordinates2)));

        bufferReader.close();
        reader.close();
    }
}
